<?php
/**
*
* @author Blackpawn blackpawn666@hotmail.com - http://blackpawnsarchives.net
* @co_author GameCharmer admin@gamecharmer.com - http://gaming.gamecharmer.com
* @package Age of Dragons Mod :: ( Game Console Required )
* @version $Id: market.php 1.1.1 12-26-2009 Blackpawn
* @copyright (c) 2009 Blackpawns Archives
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
* @ignore
*/

define('GC_MOD', true);
define('IN_PHPBB', true);
define('AOD', true);

$phpbb_root_path =  '../../';
$templates_path = '../../../games/aod/templates/';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

include($phpbb_root_path . 'common.' . $phpEx);
include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
include($phpbb_root_path . 'includes/mods/game_console/gc_common.' . $phpEx);
include($phpbb_root_path . 'games/aod/common.' . $phpEx);

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup();

// Set custom language path
$user->set_custom_lang_path($phpbb_root_path.'games/aod/language/');

//load our language file
$user->add_lang('common');

// Now add the phpBB language path
$user->set_custom_lang_path($phpbb_root_path . 'language');

// Load the Game Console language file
$user->add_lang('mods/game_console');

if ($user->data['user_id'] == ANONYMOUS)
{
	login_box('', $user->lang['LOGIN']);
}

if ($user->data['is_bot'])
{
	redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}

// Default Vars
$market_page = TRUE;	// Highlights the market tab
$error_msgs = null;
$admin = 0;
$option_1 = NULL;
$option_2 = NULL;
$option_3 = NULL;

// Var Requests
$cmd = request_var('cmd','');
$food_amount = ($_POST['1']) ? ereg_replace("[^0-9]", "", $_POST['1']):0;
$wood_amount = ($_POST['2']) ? ereg_replace("[^0-9]", "", $_POST['2']):0;
$iron_amount = ($_POST['3']) ? ereg_replace("[^0-9]", "", $_POST['3']):0;
$blackmarket = ($_POST['blackmarket']) ? ereg_replace("[^0-9]", "", $_POST['blackmarket']):0;

// AOD Config
$food_per_gold = $aod_config['food_per_gold'];
$wood_per_gold = $aod_config['wood_per_gold'];
$iron_per_gold = $aod_config['iron_per_gold'];
$market_open = $aod_config['market_open'];

// Check to see if open
if($market_open == FALSE)
{
	trigger_error($user->lang['MARKET_CLOSED'] . back_link());
}

// Gather some user info
$user_id = $user->data['user_id'];
$account_status = check_account_status($user_id);
if ($account_status == FALSE)
{
	redirect(append_sid("{$phpbb_root_path}/games/index.$phpEx"));
}

// Fetch kingdom data
$king = fetch_kingdom_data($user_id);
$admin_access = $king['admin_access'];
$kingdom_sponsor = $king['kingdom_sponsor'];
$kingdom_food = $king['kingdom_food'];
$kingdom_wood = $king['kingdom_wood'];
$kingdom_iron = $king['kingdom_iron'];
$kingdom_gold = $king['kingdom_gold'];
$kingdom_coins = $king['kingdom_coins'];
$kingdom_status = $king['kingdom_status'];

// Check to see if this user is a admin staff member
if ($user_id == 2 || $admin_access == 1)
{
	$admin = 1;
}

// Check kingdom status to see if this account is frozen
if($kingdom_status == 1)
{
	// Lets make sure the main admin can't be blocked
	if ($user_id <> 2){
		trigger_error($user->lang['FROZEN'] . back_link());
	}
}

// Configure the max amounts the user can sell
$max_food_to_sell = floor($kingdom_food / $food_per_gold); 
$max_wood_to_sell = floor($kingdom_wood / $wood_per_gold);
$max_iron_to_sell = floor($kingdom_iron / $iron_per_gold);

// Commands
if($cmd == $user->lang['SELL_RESOURCES'])
{
	// Make sure they are not trying to sell more food then they have
	if($food_amount > $max_food_to_sell)
	{
		$error = TRUE;
		$error_msgs .= $user->lang['NOT_ENOUGH_FOOD_TO_SELL'];
	}
	
	// Make sure they are not trying to sell more wood then they have
	if($wood_amount > $max_wood_to_sell)
	{
		$error = TRUE;
		$error_msgs .= $user->lang['NOT_ENOUGH_WOOD_TO_SELL'];
	}
	
	// Make sure they are not trying to sell more iron then they have
	if($iron_amount > $max_iron_to_sell)
	{
		$error = TRUE;
		$error_msgs .= $user->lang['NOT_ENOUGH_IRON_TO_SELL'];
	}	
	
	// Total up all the resources being sold
	$total_resources = ($food_amount + $wood_amount + $iron_amount);
	
	// Make sure the user is selling something
	if($total_resources < 1)
	{
		$error = TRUE;
	}	
	
	if(!$error)
	{
		// Total amount of gold needed to pay the user
		$total_gold  =	($food_amount  + $wood_amount + $iron_amount );
		 
		
		if($food_amount == 1)
		{
			$resource_msg[1] = '<span class="stextred">'.number_format($food_amount * $food_per_gold).'</span> '.$user->lang['UNIT_OF_FOOD'];
		}elseif($food_amount > 1)
		{
			$resource_msg[1] = '<span class="stextred">'.number_format($food_amount * $food_per_gold).'</span> '.$user->lang['UNITS_OF_FOOD'];
		}

		if($wood_amount == 1)
		{
			$resource_msg[2] = '<span class="stextred">'.number_format($wood_amount * $wood_per_gold).'</span> '.$user->lang['UNIT_OF_WOOD'];
		}elseif($wood_amount > 1)
		{
			$resource_msg[2] = '<span class="stextred">'.number_format($wood_amount * $wood_per_gold).'</span> '.$user->lang['UNITS_OF_WOOD'];
		}

		if($iron_amount == 1)
		{
			$resource_msg[3] = '<span class="stextred">'.number_format($iron_amount * $iron_per_gold).'</span> '.$user->lang['UNIT_OF_IRON'];
		}elseif($iron_amount > 1)
		{
			$resource_msg[3] = '<span class="stextred">'.number_format($iron_amount * $iron_per_gold).'</span> '.$user->lang['UNITS_OF_IRON'];
		}
		 
		// Build resource list
		$rmsg = build_list($resource_msg);
		
		$db->sql_query(
		"UPDATE " . AOD_KINGDOMS_TABLE ." SET 
		kingdom_gold = kingdom_gold + $total_gold,
		kingdom_food = kingdom_food - ($food_amount * $food_per_gold),
		kingdom_wood = kingdom_wood - ($wood_amount * $wood_per_gold),
		kingdom_iron = kingdom_iron - ($iron_amount * $iron_per_gold)
		WHERE user_id = $user_id");
		$db->sql_return_on_error(false);
	
		
		// Build the report
		$report = sprintf($user->lang['SUCCESSFUL_RESOURCES_SOLD'],number_format($total_gold)).$rmsg;
		
		// Log the report in the database
		report_transaction($user_id,$report,'market.php',$date);
		
		// Now it is time to redirect the user to see the report page so they can see the report
		redirect(append_sid("{$phpbb_root_path}/games/aod/report.$phpEx"));			
	}
}





if($blackmarket == TRUE)
{
	$sql = "SELECT *
	FROM " . AOD_BLACKMARKET_TABLE . "
	ORDER BY id ASC";
	$result = $db->sql_query($sql);
				
	while ($row = $db->sql_fetchrow($result))
	{
		$rid = $row['id'];
		$resource[$rid]['resource'] = $row['resource'];
		$resource[$rid]['cost'] = $row['cost'];
		$resource[$rid]['kingdom_field'] = $row['kingdom_field'];
		$resource[$rid]['kingdom_max_field'] = $row['kingdom_max_field'];
		$resource[$rid]['amount_offset'] = $row['amount_offset'];
		$resource[$rid]['operator'] = $row['operator'];
		$resource[$rid]['maxout'] = $row['maxout'];
		$resource[$rid]['buy'] = ($_POST[$rid]) ? TRUE : FALSE;	
		
		if($resource[$rid]['buy'] == TRUE)
		{
			
			if($resource[$rid]['cost'] > $kingdom_coins)
			{
				$error = TRUE;
				$error_msgs .= $user->lang['NOT_ENOUGH_COINS_TO_BUY'];
			}
	
			if(!$error)
			{
				if($resource[$rid]['maxout'] == TRUE)
				{
					$sql_str = $resource[$rid]['kingdom_field'].' = '.$resource[$rid]['kingdom_max_field'];
					
				}else{
					switch($resource[$rid]['operator'])
					{
						default: $operator = ' + '; break; // Add
						case 1: $operator = ' - '; break; // Subtract
						case 2: $operator = ' * '; break; // Multiply
						case 3: $operator = ' / '; break; // Divide Not sure this one will ever be used but just in case lol
					}
					
					$sql_str = $resource[$rid]['kingdom_field'].' = '.$resource[$rid]['kingdom_field'].$operator.$resource[$rid]['amount_offset'];
				}
	
				$cost =  $resource[$rid]['cost'];
			
				$db->sql_query(
				"UPDATE " . AOD_KINGDOMS_TABLE ." SET
				kingdom_coins = kingdom_coins - $cost,
				$sql_str
				WHERE user_id = $user_id");
				$db->sql_return_on_error(false);
			
				// Build the report
				$report = sprintf($user->lang['BLACKMARKET_PURCHASE'],$resource[$rid]['resource'],number_format($resource[$rid]['cost']));
				
				// Log the report in the database
				report_transaction($user_id,$report,'market.php',$date);
				
				// Now it is time to redirect the user to see the report page so they can see the report
				redirect(append_sid("{$phpbb_root_path}/games/aod/report.$phpEx"));	
			}
			
		}
	}
	$db->sql_freeresult($result);	
}
			
			
// Build unit list	
$sql = "SELECT *
FROM " . AOD_BLACKMARKET_TABLE . "	
ORDER BY id ASC";
$result = $db->sql_query($sql);
			
while ($row = $db->sql_fetchrow($result))
{

	$rid = $row['id'];
	$resource = $row['resource'];
	$cost = $row['cost'];

	$template->assign_block_vars('blackmarketrow', array(
		'RESOURCE'		=> $resource,
		'DRAGON_COINS'	=> number_format($cost),
		'ID'			=> $rid,
	
		)
	);	
}	
$db->sql_freeresult($result);

// Display an error messages to the user
if($error_msgs){
	$error_msgs = '<span class="errormsg"><b>'.$error_msgs.'</b></span>';
}

$template->assign_vars(array(
	
	'FOOD_PRICE'			=> sprintf($user->lang['RESOURCE_PER_GOLD'] , $food_per_gold),
	'FOOD_MAX'				=> number_format($max_food_to_sell),
	
	'WOOD_PRICE'			=> sprintf($user->lang['RESOURCE_PER_GOLD'] , $wood_per_gold),
	'WOOD_MAX'				=> number_format($max_wood_to_sell),
	
	'IRON_PRICE'			=> sprintf($user->lang['RESOURCE_PER_GOLD'] , $iron_per_gold),
	'IRON_MAX'				=> number_format($max_iron_to_sell),

	'GOLD_FROM_FOOD_MAX'	=> number_format($max_food_to_sell),
	'GOLD_FROM_WOOD_MAX'	=> number_format($max_wood_to_sell),
	'GOLD_FROM_IRON_MAX'	=> number_format($max_iron_to_sell),

	'OPTION_1'				=> $option_1,
	'OPTION_2'				=> $option_2,
	'OPTION_3'				=> $option_3,
	'DRAGON_COINS'			=> sprintf($user->lang['AVAILABLE_DRAGON_COINS'] ,number_format($kingdom_coins)),

	)
);

include($phpbb_root_path . 'games/aod/includes/page_header.' . $phpEx);


// Output page
page_header($game_name.' - '.$user->lang['MARKET']);

$template->set_filenames(array(
	'body' => $templates_path.'market_body.html')
);

page_footer();
?>